package com.sgcc.activiti.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Maps;
import com.sgcc.activiti.domain.*;
import com.sgcc.activiti.service.IOContentAppService;
import com.sgcc.activiti.service.IProcessService;
import com.sgcc.common.core.utils.DateUtils;
import com.sgcc.common.core.utils.SecurityUtils;
import com.sgcc.common.core.utils.StringUtils;
import com.sgcc.common.core.utils.bean.BeanUtils;
import com.sgcc.common.security.service.TokenService;
import com.sgcc.system.api.domain.SysDictData;
import com.sgcc.system.api.domain.SysRole;
import com.sgcc.system.api.domain.SysUser;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.Model;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.sgcc.common.log.annotation.Log;
import com.sgcc.common.log.enums.BusinessType;
import com.sgcc.common.security.annotation.PreAuthorize;
import com.sgcc.activiti.service.IOContentAppSchemaService;
import com.sgcc.common.core.web.controller.BaseController;
import com.sgcc.common.core.web.domain.AjaxResult;
import com.sgcc.common.core.utils.poi.ExcelUtil;
import com.sgcc.common.core.web.page.TableDataInfo;

/**
 * 资讯查询Controller
 * 
 * @author sgcc
 * @date 2021-04-07
 */
@RestController
@RequestMapping("/OContentAppSchema")
public class OContentAppSchemaController extends BaseController
{
    @Autowired
    private IOContentAppSchemaService oContentAppSchemaService;
    @Autowired
    private IProcessService processService;

    @Autowired
    private IOContentAppService oContentAppService;

    @Log(title = "提交资讯流程", businessType = BusinessType.UPDATE)
    @PostMapping( "/submitApply/{id}")
    @ResponseBody
    public AjaxResult submitApply(@PathVariable String id) {
        try {
            OContentAppSchema obj = oContentAppSchemaService.selectOContentAppSchemaById(id);
            processService.submitApply(obj, "app");
            oContentAppSchemaService.updateOContentAppSchema(obj);
        } catch (Exception e) {
            e.printStackTrace();
            return error("提交申请出错：" + e.getMessage());
        }
        return success();
    }
    /**
     * 查询资讯查询列表
     */
    //@PreAuthorize(hasPermi = "activiti:OContentAppSchema:list")
    @GetMapping("/list")
    public TableDataInfo list(OContentAppSchema oContentAppSchema)
    {
        startPage();
        List<OContentAppSchema> list = oContentAppSchemaService.selectOContentAppSchemaList(oContentAppSchema);
        return getDataTable(list);
    }

    //@PreAuthorize(hasPermi = "activiti:OContentAppSchema:list")
    @GetMapping("/listProcess")
    public TableDataInfo listProcess(OContentAppSchema oContentAppSchema)
    {
        startPage();

        List<OContentAppSchema> list = oContentAppSchemaService.selectOContentAppSchemaListProcess(oContentAppSchema);
        return getDataTable(list);
    }

    //@PreAuthorize(hasPermi = "activiti:OContentAppSchema:list")
    @GetMapping("/listSubmitist")
    public TableDataInfo listSubmitist(OContentAppSchema oContentAppSchema)
    {
        startPage();

        List<OContentAppSchema> list = oContentAppSchemaService.selectOContentAppSchemaSubmitist(oContentAppSchema);
        return getDataTable(list);
    }

    /**
     * 导出资讯查询列表
     */
    //@PreAuthorize(hasPermi = "activiti:OContentAppSchema:export")
    @Log(title = "资讯查询", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OContentAppSchema oContentAppSchema) throws IOException
    {
        List<OContentAppSchema> list = oContentAppSchemaService.selectOContentAppSchemaList(oContentAppSchema);
        ExcelUtil<OContentAppSchema> util = new ExcelUtil<OContentAppSchema>(OContentAppSchema.class);
        util.exportExcel(response, list, "OContentAppSchema");
    }

    /**
     * 获取资讯查询详细信息
     */
    //@PreAuthorize(hasPermi = "activiti:OContentAppSchema:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(oContentAppSchemaService.selectOContentAppSchemaById(id));
    }

    /**
     * 新增资讯查询
     */
    //@PreAuthorize(hasPermi = "activiti:OContentAppSchema:add")
    @Log(title = "新增资讯", businessType = BusinessType.INSERT)
    @PostMapping("/addOContentAppSchemaSave")
    public AjaxResult addOContentAppSchemaSave(@RequestBody OContentAppSchema oContentAppSchema)
    {
        Integer num=oContentAppSchemaService.selectOContentAppByNewId(oContentAppSchema.getNewId());
        if(num>0){
            return AjaxResult.error("已在进行流程~");
        }

        return toAjax(oContentAppSchemaService.insertOContentAppSchema(oContentAppSchema));
    }
    @Log(title = "新增资讯", businessType = BusinessType.INSERT)
    @PostMapping("/addOContentAppSchemaSubmit")
    public AjaxResult addOContentAppSchemaSubmit(@RequestBody OContentAppSchema oContentAppSchema)
    {
        if(null!=oContentAppSchema.getNewId()){
            Integer num=oContentAppSchemaService.selectOContentAppByNewId(oContentAppSchema.getNewId());
            if(num>0){
                return AjaxResult.error("已在进行流程~");
            }
        }
        Integer i=oContentAppSchemaService.insertOContentAppSchema(oContentAppSchema);
        OContentAppSchema OContentAdSchema=oContentAppSchemaService.selectOContentAppSchemaById(oContentAppSchema.getId());
        try {
            processService.richProcessField(OContentAdSchema);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String taskId = OContentAdSchema.getTaskId();
        String instanceId = OContentAdSchema.getInstanceId();
        JSONObject obj=new JSONObject();
        obj.put("pass",true);
        obj.put("comment","同意");
        obj.put("formData",OContentAdSchema);
        String variables = obj.toString();

        AjaxResult  result= processService.complete(taskId, instanceId, variables);
        return toAjax(i);
    }

    /**
     * 修改资讯查询
     */
    //@PreAuthorize(hasPermi = "activiti:OContentAppSchema:edit")
    @Log(title = "资讯查询", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OContentAppSchema oContentAppSchema)
    {
        return toAjax(oContentAppSchemaService.updateOContentAppSchema(oContentAppSchema));
    }

    /**
     * 删除资讯查询
     */
    //@PreAuthorize(hasPermi = "activiti:OContentAppSchema:remove")
    @Log(title = "资讯查询", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(oContentAppSchemaService.deleteOContentAppSchemaByIds(ids));
    }

    /**
     * 资讯流程下拉框信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "flowTypes", method = RequestMethod.GET)
    //@ApiOperation(notes = "flowTypes", httpMethod = "GET", value = "资讯流程下拉框信息")
    // @ControllerLog(description = "资讯流程下拉框信息", module = "内容管理模块", logType = LogType.ServiceType)
    public Map<String,Object> flowTypes(){
        List<SysDictData> dictTypes = oContentAppSchemaService.getValueByType("flowType");
        Map map = new HashMap(16);
        map.put("rows",dictTypes);
        return map;
    }


    /**
     * 资讯查询数据
     */
    @ResponseBody
//	@RequiresPermissions("goshine:ocontentad:oContentAd:list")
    @RequestMapping(value = "findAppList")
    @ApiOperation(notes = "findAppList", httpMethod = "POST", value = "资讯查询")
    @ApiImplicitParams({
            // 流程状态，采用标准编码 flowType 01	待提交 02	待审核 03	待发布 04	待反馈 05	发布失败 06	结束 07	待提交-审核不通过 08	终止
            @ApiImplicitParam(name = "flowType", value = "flowType", required = false, paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "startTime", value = "startTime", required = false, paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "endTime", value = "endTime", required = false, paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = true, paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小", required = true, paramType = "query",dataType = "string")
    })
    // @ControllerLog(description = "资讯查询", module = "内容管理模块", logType = LogType.ServiceType)
    public TableDataInfo findAppList(String flowType,
                                           String startTime,
                                           String endTime,
                                           String appId,
                                           String orderNo,
                                           String contentTitle,
                                           HttpServletRequest request,
                                           HttpServletResponse response,
                                           Model model) throws Exception {
        OContentApp oContentApp = new OContentApp();
        oContentApp.setFlowType(flowType);
        if(StringUtils.isNotBlank(startTime)){
            startTime = DateUtils.judgeStatTime(startTime)+" 00:00:00";
        }
        if(StringUtils.isNotBlank(endTime)){
            endTime = DateUtils.judgeStatTime(endTime)+" 23:59:59";
        }
        oContentApp.setStartTime(startTime);
        oContentApp.setEndTime(endTime);
        oContentApp.setAppId(appId);
        oContentApp.setContentTitle(contentTitle);
        oContentApp.setOrderNo(orderNo);
        List<OContentApp> pageList = oContentAppService.findAppList(oContentApp);
        return getDataTable(pageList);
    }


    /**
     * 展示频道信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "sceneData", method = RequestMethod.GET)
    @ApiOperation(notes = "sceneData", httpMethod = "GET", value = "展示频道信息")
    // @ControllerLog(description = "展示频道信息", module = "内容管理模块", logType = LogType.ServiceType)
    public Map<String, Object> sceneData(String id) throws Exception {
        Map map = new HashMap(16);
        map.put("rows",oContentAppSchemaService.sceneDta(id));
        return map;
    }


    /**
     * 保存资讯维护方案并启动流程（新增或者变更）
     */
    @ResponseBody
    @RequestMapping(value = "saveEx", method = RequestMethod.POST)
    @ApiOperation(notes = "saveEx", httpMethod = "POST", value = "保存资讯维护方案并启动流程")
    // @ControllerLog(description = "保存资讯维护方案并启动流程", module = "内容管理模块", logType = LogType.ServiceType)
    public AjaxResult saveEx(OContentAppSchema oContentAppSchemaVo, Model model, String submitType) throws Exception {

        long time = System.currentTimeMillis();
        Date date1 = new Date(time);
        SimpleDateFormat sf = new SimpleDateFormat("YYYYMMddHHmmssSSS");
        // 维护类型，操作类型：serviceType 01	新增 02	变更 03	下架
        String serviceType = oContentAppSchemaVo.getServiceType();
        //用户
//        SysUser user = tokenService.getLoginUser().getSysUser();

        //id
        String id = oContentAppSchemaVo.getId();
        //流程实例ID
        String oldProcInsId = oContentAppSchemaVo.getProcInsId();
        //总部业务唯一标识
        String newId = oContentAppSchemaVo.getNewId();
        String typeName = null;
        Map<String, Object> vars = Maps.newHashMap();
        vars.put("termination", 0);
        // submitType 0:保存 1:提交
        if ("0".equals(submitType)) {
            //第一次进入，需保存业务数据并发起流程；
            //后续只保存业务数据，不处理流程
            if (StringUtils.isBlank(oldProcInsId)) {
                //封装业务数据
                if ("01".equals(serviceType)) {
                    // 总部业务唯一标识，网上国网资讯ID
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    oContentAppSchemaVo.setNewId(uuid);
                    typeName = "新增";
                }else {
                    typeName = "变更";
                }
                // 当前环节，包括流程的环节，有结束、终止等
                oContentAppSchemaVo.setActName("资讯维护");
                //流采用标准编码 flowType 01待提交 02待审核 03待发布 04待反馈 05发布失败 06结束 07待提交-审核不通过 08终止
                oContentAppSchemaVo.setFlowType("01");
                oContentAppSchemaVo.setArriveTime(date1);

                //保存并发起流程
                //新增表单
                oContentAppSchemaService.saveEx(oContentAppSchemaVo);

                /**
                 * 发起流程*/

//                processService.submitApply(oContentAppSchemaVo, "leave");
                oContentAppSchemaService.updateOContentAppSchema(oContentAppSchemaVo);

                /**
                 * 结果表信息*/

                if ("02".equals(serviceType) || "03".equals(serviceType)) {
                    if (StringUtils.isNotBlank(newId)) {
                        OContentApp oContentAppCondition = new OContentApp();
                        oContentAppCondition.setNewId(newId);
                        List<OContentApp> oContentAppServiceList = oContentAppService.selectOContentAppList(oContentAppCondition);
                        if (oContentAppServiceList.size() > 0 && null != oContentAppServiceList.get(0)) {
                            OContentApp oContentApp = oContentAppServiceList.get(0);
                            oContentApp.setOrderNo(sf.format(date1));
                            // oContentApp.setAppNo(procInsId);
                            oContentApp.setRemarks(null);
                            oContentApp.setServiceType(oContentAppSchemaVo.getServiceType());
                            oContentAppService.updateOContentApp(oContentApp);
                        }
                    }
                }else{
//                    OContentApp oContentApp = new OContentApp();
//                    BeanUtils.copyProperties(oContentAppSchemaVo, oContentApp);
////                    oContentApp.setIsNewRecord(false);
////                    oContentApp.setAppNo(procInsId);
//                    oContentApp.setId(null);
//                    oContentApp.setDelFlag("0");
//                    oContentAppService.insertOContentApp(oContentApp);
                }

                logger.info("已成功发起"+typeName+"流程编号"+"<br/>"+sf.format(date1));
                return AjaxResult.success("已成功发起"+typeName+"流程编号"+"<br/>"+sf.format(date1));
            }else {
                if (StringUtils.isBlank(id)) {
                    return AjaxResult.error(400,"缺少参数");
                }
                OContentAppSchema oContentAppSchema = oContentAppSchemaService.selectOContentAppSchemaById(id);
                //后续只保存业务数据，不处理流程
                //编辑表单
                // OContentAppSchema.editContent(oContentAppSchemaVo,oContentAppSchema);
                oContentAppSchemaService.saveEx(oContentAppSchema);
                return AjaxResult.success("资讯保存成功!");
            }
        }else if ("1".equals(submitType)) {
            // submitType  1:提交 ： 流程从 待提交 ---》 待审核
            //保存并发起流程&&完成当前节点
            if (StringUtils.isBlank(oldProcInsId)) {
                //封装业务数据
                if ("01".equals(serviceType)) {
                    // 总部业务唯一标识，网上国网资讯ID
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    oContentAppSchemaVo.setNewId(uuid);
                    typeName = "新增";
                }else {
                    typeName = "变更";
                }
                // 当前环节，包括流程的环节，有结束、终止等
                oContentAppSchemaVo.setActName("资讯审核");
                //流采用标准编码 flowType 01待提交 02待审核 03待发布 04待反馈 05发布失败 06结束 07待提交-审核不通过 08终止
                oContentAppSchemaVo.setFlowType("02");
                oContentAppSchemaVo.setArriveTime(date1);
                /*if(StringUtils.isBlank(oContentAppSchemaVo.getOrderNo())){
                    oContentAppSchemaVo.setOrderNo(sf.format(date1));
                }*/
                //新增表单
                oContentAppSchemaService.saveEx(oContentAppSchemaVo);

               /* *
                 * 结果表信息*/

                if ("02".equals(serviceType) || "03".equals(serviceType)) {
                    if (StringUtils.isNotBlank(newId)) {
                        OContentApp oContentAppCondition = new OContentApp();
                        oContentAppCondition.setNewId(newId);
                        List<OContentApp> oContentAppServiceList = oContentAppService.selectOContentAppList(oContentAppCondition);
                        if (oContentAppServiceList.size() > 0 && null != oContentAppServiceList.get(0)) {
                            OContentApp oContentApp = oContentAppServiceList.get(0);
                            oContentApp.setOrderNo(sf.format(date1));
//                            oContentApp.setAppNo(procInsId);
                            oContentApp.setServiceType(oContentAppSchemaVo.getServiceType());
                            oContentAppService.updateOContentApp(oContentApp);
                        }
                    }
                }else{
                    OContentApp oContentApp = new OContentApp();
                    BeanUtils.copyProperties(oContentAppSchemaVo, oContentApp);
//                    oContentApp.setIsNewRecord(false);
//                    oContentApp.setAppNo(procInsId);
                    oContentApp.setId(null);
                    oContentApp.setDelFlag("0");
                    oContentAppService.insertOContentApp(oContentApp);
                }

                logger.info("已成功发起"+typeName+"流程编号"+"<br/>"+sf.format(date1));
                return AjaxResult.success("已成功发起"+typeName+"流程编号"+"<br/>"+sf.format(date1));
            } else {
                if (StringUtils.isBlank(id)) {

                    return AjaxResult.error(400,"缺少参数");
                }
                OContentAppSchema oContentAppSchema = oContentAppSchemaService.selectOContentAppSchemaById(id);
                // OContentAppSchema.editContent(oContentAppSchemaVo,oContentAppSchema);
                //编辑表单
                // 当前环节，包括流程的环节，有结束、终止等
                oContentAppSchema.setActName("资讯审核");
                //流采用标准编码 flowType 01待提交 02待审核 03待发布 04待反馈 05发布失败 06结束 07待提交-审核不通过 08终止
                oContentAppSchema.setFlowType("02");
                oContentAppSchema.setArriveTime(date1);
                oContentAppSchemaService.saveEx(oContentAppSchema);
                return AjaxResult.success("资讯流程提交成功!");
            }
        }
        return new AjaxResult();
    }


    /**
     * 资讯发布
     */
    @ResponseBody
    @RequestMapping(value = "publish", method = RequestMethod.POST)
    @ApiOperation(notes = "publish", httpMethod = "POST", value = "资讯发布")
    // @ControllerLog(description = "资讯发布", module = "内容管理模块", logType = LogType.ServiceType)
    public AjaxResult publish(@RequestBody OContentAppSchema oContentAppSchema) throws Exception {
        return oContentAppSchemaService.publish(oContentAppSchema);
    }

    /**
     * 资讯审核
     */
    @ResponseBody
    @RequestMapping(value = "audit", method = RequestMethod.POST)
    @ApiOperation(notes = "audit", httpMethod = "POST", value = "资讯审核")
    // @ControllerLog(description = "资讯审核", module = "内容管理模块", logType = LogType.ServiceType)
    public AjaxResult audit(OContentAppSchema oContentAppSchema, String auditType,String comment) throws Exception {
        return oContentAppSchemaService.audit(oContentAppSchema,auditType,comment);
    }
}
